package com.zmn.brs.business.impl.base;

import com.alibaba.fastjson.JSONObject;
import com.zmn.brs.business.interfaces.base.BaseBService;
import com.zmn.brs.common.constant.RedisKeyConst;
import com.zmn.brs.common.enums.ThresholdTypeEnum;
import com.zmn.brs.model.bo.rule.CacheThresholdBO;
import com.zmn.brs.model.entity.event.EventBase;
import com.zmn.brs.services.interfaces.event.EventService;
import com.zmn.plat.common.dictionary.StatusEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 * 描述： 安全监控实现
 *
 * @author chongw
 * @since 2021-07-08 9:55
 */
@Slf4j
@Service
public class BaseBServiceImpl<T> implements BaseBService<T> {

    final static String TAG = "安全监控实现";

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    @Resource
    private EventService eventService;

    /**
     * 根据事件类型获取当前事件下规则公共阈值
     * @param eventType
     * @return
     */
    @Override
    public <T> T getCommonThreshold(Integer eventType){
        //获取唯一key
        String redisKey = RedisKeyConst.getCacheRuleConfigRedisKey(eventType, ThresholdTypeEnum.COMMON.name().toLowerCase());
        Object value = redisTemplate.opsForValue().get(redisKey);
        Class <T> clazz = (Class <T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
        if(value != null){
            return JSONObject.parseObject(value.toString(),clazz);
        }
        try {
            return clazz.newInstance();
        }catch (Exception e){

        }
        return null;
    }

    /**
     * 根据事件类型获取当前事件下规则公共阈值
     * @param eventType
     * @return
     */
    @Override
    public Double getCommonThresholdValue(Integer eventType){
        //获取唯一key
        String redisKey = RedisKeyConst.getCacheRuleConfigRedisKey(eventType, ThresholdTypeEnum.COMMON.name().toLowerCase());
        Object value = redisTemplate.opsForValue().get(redisKey);
        if(value != null){
            return JSONObject.parseObject(value.toString()).getDoubleValue("value");
        }
        try {
            Class <T> clazz = (Class <T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
            Method m = clazz.getMethod(
                    "getValue" );
            Object val = m.invoke(clazz.newInstance());
            if(val != null){
                return Double.parseDouble(val.toString());
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return 0D;
    }

    /**
     * 检查状态
     * @param configRedisKey
     * @return
     */
    @Override
    public Boolean checkStatus(String configRedisKey){
        //配置的阈值
        CacheThresholdBO configData = this.getRuleConfigValue(configRedisKey);

        return checkStatus(configData);
    }

    /**
     * 检查状态
     * @param configData
     * @return
     */
    @Override
    public Boolean checkStatus(CacheThresholdBO configData){
        //获取场景状态
        String sceneRedisKey = RedisKeyConst.getStatusRedisKey(RedisKeyConst.SCENE_STATUS_REDIS_KEY , configData.getSceneId());
        if(redisTemplate.hasKey(sceneRedisKey)
                && StatusEnum.DISABLE.getCode().equals(redisTemplate.opsForValue().get(sceneRedisKey))){
            log.error("[{}], 当前场景状态已被停用！！！，场景ID：{}", TAG, configData.getSceneId());
            return false;
        }
        //获取事件状态
        String eventRedisKey = RedisKeyConst.getStatusRedisKey(RedisKeyConst.EVENT_STATUS_REDIS_KEY , configData.getEventId());
        if(redisTemplate.hasKey(eventRedisKey)
                &&  StatusEnum.DISABLE.getCode().equals(redisTemplate.opsForValue().get(eventRedisKey))){
            log.error("[{}], 当前事件状态已被停用！！！，事件ID：{}", TAG, configData.getEventId());
            return false;
        }
        //获取规则阈值状态
        String ruleRedisKey = RedisKeyConst.getStatusRedisKey(RedisKeyConst.THRESHOLD_STATUS_REDIS_KEY , configData.getThresholdId());
        if(redisTemplate.hasKey(ruleRedisKey)
                &&  StatusEnum.DISABLE.getCode().equals(redisTemplate.opsForValue().get(ruleRedisKey))){
            log.error("[{}], 当前规则阈值状态已被停用！！！，规则阈值ID：{}", TAG, configData.getThresholdId());
            return false;
        }
        return true;
    }
    /**
     * 获取配置 整体单量的阈值
     * @param redisKey
     * @return
     */
    @Override
    public CacheThresholdBO getRuleConfigValue(String redisKey){
        Object value = redisTemplate.opsForValue().get(redisKey);
        if(value != null){
            return JSONObject.parseObject(String.valueOf(value) , CacheThresholdBO.class);
        }
        return null;
    }

    /**
     * 获取事件群机器人ID
     * @param eventType
     * @return
     */
    @Override
    public Integer getRobotId(Integer eventType){
        //获取推送机器人
        List<EventBase> baseList = Optional.ofNullable(eventService.listByEventType(eventType)).orElse(new ArrayList<>());
        if(!baseList.isEmpty() && baseList.get(0) != null){
            EventBase base = baseList.get(0);
            Integer status = eventService.getStatusByEventId(base.getEventId());
            //判断状态是否禁用
            if (StatusEnum.DISABLE.getCode().equals(status)) {
                log.info("[{}], eventId：{}，事件已被禁用 ！！！", TAG, base.getEventId());
                return null;
            }
            return baseList.get(0).getRobotId();
        }
        return null;
    }
}
